const errors = require('../../errors')
var WXBizDataCrypt = require('../../util/WXBizDataCrypt')
const Validate = require('../../util/baseUtil/Validate')
const mongoose = require('mongoose')
const moment = require('moment')
const request = require('request')
const appid = 'wx15bd640984145f64'
const secret = 'd2773a4639dc52e04fe03cd2c38cf07c'
var async = require('async')
var multiparty = require('multiparty');
var fs = require('fs')
var mkdirp = require('mkdirp');
var easyimage = require('easyimage')
const LogUtil = require('../../util/baseUtil/LogUtil')
const ObjectID = require('mongodb').ObjectID;
var wxpay = require('../../util/wxpay')
const xmlParse = require('xml2js').parseString
const sha1 = require('js-sha1');


const User = require('../../model/User.js')

const Role = require('../../model/Role.js')

const Recommendation = require('../../model/Recommendation')
const Store = require('../../model/Store')
const Product = require('../../model/Product')
const Activity = require('../../model/Activity')
const Coupon = require('../../model/Coupon')
const Cart = require('../../model/Cart')
const Member = require('../../model/Member')
const Order = require('../../model/Order')
const Banner = require('../../model/Banner')
const ProductCategory = require('../../model/ProductCategory')
const MyFavorite = require('../../model/MyFavorite')
const ProductSub = require('../../model/ProductSub')
const ExpenseHistory = require('../../model/ExpenseHistory')
const MemberCard = require('../../model/MemberCard')
const UserPoint = require('../../model/userPoint')
const Advertisement = require('../../model/Advertisement')
const Dish = require('../../model/Dish')
const ShowActivity = require('../../model/ShowActivity')
const Staff = require('../../model/Staff')
const PointHistory = require('../../model/PointHistory')
const Rules = require('../../model/Rules')
const Voucher = require('../../model/Voucher')
const SourceStatistics = require('../../model/SourceStatistics')
const MyVoucher = require('../../model/MyVoucher')
const Reimburse = require('../../model/Reimburse')
const Address = require('../../model/Address')
const NewcomerGift = require('../../model/NewcomerGift')

const SMSQQ = require('../../util/businessUtil/smsQQ.js')

const TencentID = 'AKIDWrxoQbqDvSkmgNp120jaENJ0Rcke7ivf'
const TencentPWD = 'g6HQL1RfiV7UnxrW3NTKwKQL1RM1RecR'
const wxPublicAccessToken = require('../../util/businessUtil/wxPublicAccessToken')
// const TencentAPP = '1300737392'

const COS = require('cos-nodejs-sdk-v5');
const cos = new COS({
    SecretId: TencentID,
    SecretKey: TencentPWD
});



module.exports = {

    uploadTest: async (req, res, next) => {
        let filepath = 'public/img/we.4a393768.jpg'
        let smp = fs.readFileSync(filepath)
        console.log(smp)

        cos.putObject({
            Bucket: 'yifei-1300737392',
            Region: 'ap-beijing',
            Key: '/image/test.jpg', // 这里传入前缀
            Body: smp,
        }, function (err, data) {
            console.log(err);
            console.log(data.Location)
        });
    },

    wxlogin: async (req, res, next) => {
        try {
            // console.log('run', req.body)
            let jscode = req.body.code
            if (jscode) {
                var wxurl = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + jscode + '&grant_type=authorization_code'
                request({
                    url: wxurl,
                    method: "GET",
                    timeout: 10000,
                    followRedirect: true,
                    maxRedirects: 10
                }, function (error, response, body) {
                    console.log('body', body)
                    if (error) {
                        res.send({ 'error': 400 })
                    } else {
                        // check if in db , if not in db ,create one
                        var newbody = JSON.parse(body)
                        var session_key = newbody.session_key
                        let encryptedData = req.body.encryptedData
                        encryptedData = encryptedData.replace(' ', '+')
                        let iv = req.body.iv
                        try {
                            var pc = new WXBizDataCrypt(appid, session_key)
                            var userData = pc.decryptData(encryptedData, iv)
                        } catch (e) {
                            // redisClient.del(req.body.token)
                            res.send({ 'code': 401 })
                            return false
                        }
                        var openid = userData.openId
                        var unionid = userData.unionId
                        // var unionid = userData.openId
                        User.findOne({ $or: [{ unionID: unionid }, { openid: openid }] }, function (err, data) {
                            let cellphone = ''
                            if (data != null && data.cellphone != null) {
                                cellphone = data.cellphone
                            }
                            if (data == null) {
                                initializeUser(openid, unionid, cellphone, req.body.userInfo, req.body.way, req.body.QRStore, req.body.QRType, function (err) {
                                    redisClient.set(req.sessionID, JSON.stringify({ openid: openid, unionid: unionid, session_key: session_key }), function (err, success) {
                                        redisClient.expireat(req.sessionID, parseInt(new Date().getTime() / 1000) + 30 * 86400, function (err, ress) {
                                            res.send({ 'code': 200, 'token': req.sessionID, 'userInfo': req.body.userInfo, cellphone: cellphone })
                                        })
                                    })
                                })
                            } else {
                                initializeUser(openid, unionid, cellphone, req.body.userInfo, req.body.way, req.body.QRStore, req.body.QRType, function (err) {

                                    redisClient.set(req.sessionID, JSON.stringify({ openid: openid, unionid: unionid, session_key: session_key }), function (err, success) {
                                        redisClient.expireat(req.sessionID, parseInt(new Date().getTime() / 1000) + 30 * 86400, function (err, ress) {
                                            res.send({ 'code': 200, 'token': req.sessionID, 'userInfo': req.body.userInfo, cellphone: cellphone })
                                        })
                                    })
                                })
                            }
                        })
                    }
                })
            } else {
                res.send({ 'error': 400 })
            }
        } catch (e) {
            next(e)
        }
    },

    sendcode: async (req, res, next) => {

        var cellphone = req.body.cellphone
        var code = String(randomsixdigit())
        // res.send({ 'code': 200 })
        SMSQQ.sendVerification(code, cellphone, function (err, response, resData) {
            if (resData.errmsg == 'OK') {
                redisClient.set(cellphone, code, 'ex', 1800, function (err) {
                    console.log(code)
                    res.send({ 'code': 200 })
                })
            } else {
                res.send({ 'code': 400 })
            }
        })

        // res.ok('验证码')//验证码代码
    },

    verifyCodeAndUpdate: async (req, res, next) => { //手机验证代码
        try {
            redisClient.get(req.body.cellphone, async function (err, data) {
                if (data == undefined) {
                    console.log('1')
                    res.send({ 'code': 202 })
                    return false
                } else if (data != req.body.code) {
                    console.log('2')
                    res.ok('验证码错误')
                    return false
                } else {
                    redisClient.del(req.body.cellphone)
                    let user = await User.findOne({ cellphone: req.body.cellphone, isDelete: 0 }).exec()
                    if (user != null) {
                        console.log('3')
                        redisClient.del(req.body.cellphone)
                        res.send({ 'code': 201, msg: '手机号已被使用' })
                    } else {
                        console.log('4')
                        let user = await User.findOne({ unionID: req.body.unionid, isDelete: 0 }).exec()
                        user.cellphone = req.body.cellphone
                        user.lastFour = req.body.cellphone.substr(req.body.cellphone.length - 4, 4)
                        await user.save()
                        redisClient.set(req.sessionID, JSON.stringify({ openid: req.body.openid, unionid: req.body.unionid }), function (err, success) {
                            redisClient.expireat(req.sessionID, parseInt(new Date().getTime() / 1000) + 30 * 86400, function (err, ress) {
                                res.send({ 'code': 200, 'token': req.sessionID, 'userInfo': req.body.userInfo, cellphone: req.body.cellphone })
                            })
                        })
                        // res.ok('手机号验证成功')
                    }
                }
            })




            // let staff = await Staff.findOne({ cellphone: req.body.cellphone, isDelete: 0 }, '_id').exec();
            // if (staff == null) {
            //     res.send({ 'code': 201, msg: 'notfound' })
            //     return false
            // } else {



            //     let openid = req.body.openid
            //     let options = {}
            //     options.staff = staff._id
            //     options.cellphone = req.body.cellphone
            //     redisClient.set(req.body.token, JSON.stringify({ staffId: String(staff._id), openid: openid }), function(err, success) {
            //         redisClient.expireat(req.body.token, parseInt(new Date().getTime() / 1000) + 30 * 86400, function(err, ress) {
            //             WechatUser.updateOne({ openid: openid }, options).exec(function(err, user) {
            //                 res.send({ 'code': 200, staff: staff._id })
            //             })
            //         })
            //     })
            // }

        } catch (e) {
            next(e)
        }
    },
    updateCellphone: async (req, res, next) => { //手机验证代码
        try {
            // console.log(req.body)
            let iv = req.body.iv
            let encryptedData = req.body.encryptedData
            encryptedData = encryptedData.replace(' ', '+')
            let session_key = req.body.session_key
            try {
                var pc = new WXBizDataCrypt(appid, session_key)
                var phoneData = pc.decryptData(encryptedData, iv)
            } catch (e) {
                redisClient.del(req.body.token)
                res.send({ 'code': 401 })
                return false
            }
            var phone = phoneData.phoneNumber
            let user = await User.findOne({ cellphone: phone, openid: { $ne: req.body.openid }, isDelete: 0 }).exec()
            if (user != null) {
                res.send({ 'code': 201, msg: '手机号已被使用' })
            } else {
                let user = await User.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
                if (user == null) {
                    res.send({ code: 401 })
                }
                user.cellphone = phone
                user.lastFour = phone.substr(phone.length - 4, 4)
                await user.save()
                res.ok('手机号保存成功', phone)
            }
        } catch (e) {
            next(e)
        }
    },
    homePageBanner: async (req, res, next) => {
        try {
            let banner = await Banner.findOne({ page: "index" }).exec()
            let data = {}
            data.images = banner.image
            data.refLink = banner.refLink
            res.ok('获取轮播图成功', data)
        } catch (e) {
            next(e)
        }
    },
    getBanner: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            if (req.body.pageType) {
                options.page = req.body.pageType
            }
            let banner = await Banner.findOne(options).exec()
            let data = {}
            data.images = banner.image
            data.refLink = banner.refLink
            res.ok('获取轮播图成功', data)
        } catch (e) {
            next(e)
        }
    },
    homePageRecommend: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            options.page = { $in: 'index' }
            let data = await Recommendation.findOne(options).populate({
                path: 'detail.product',
                model: Product
            }).populate({
                path: 'detail.store',
                model: Store
            }).populate({
                path: 'detail.dish',
                model: Dish
            }).populate({
                path: 'detail.activity',
                model: Activity
            }).populate({
                path: 'detail.voucher',
                model: Voucher,
                populate: { path: 'voucher' }
            }).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || data.detail.length
            let start = (page - 1) * pageSize
            let end = page * pageSize
            let result = {}
            result.total = data.detail.length
            result.currentPage = page
            result.pageSize = pageSize
            result.data = data.detail.slice(start, end)
            res.ok('获取推荐成功', result)
        } catch (e) {
            next(e)
        }
    },
    homePageRecommendStore: async (req, res, next) => {
        try {
            let data = []
            let recommendation = await Recommendation.findOne({ page: "homePageRecommendationStore", isDelete: 0 }).populate({
                path: 'detail.store',
                model: Store
            }).exec()
            data = recommendation.detail.map(e => { return e.store })
            data = data.slice(0, req.body.limit)
            return res.ok('查询成功', data)
            // let limit = req.body.limit || 1
            // let store = await Store.find({ location: { $near: [req.body.latitude, req.body.longitude, ] }, isDelete: 0, status: 1 }).limit(limit).exec()
            // res.ok('门店获取成功', store)
        } catch (e) {
            next(e)
        }
    },
    homePageProduct: async (req, res, next) => {
        try {
            let count = await Product.countDocuments().exec()
            let page = req.body.page || 1
            let pageSize = 10
            let data = await Product.find().skip((page - 1) * pageSize).limit(pageSize).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('商品获取成功', result)
        } catch (e) {
            next(e)
        }
    },
    storeList: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            options.status = 1
            if (req.body.keywords) {
                options = { $or: [{ name: new RegExp(req.body.keywords, 'i') }, { address: new RegExp(req.body.keywords, 'i') }] }
            }
            if (req.body.label) {
                options.label = { $in: req.body.label }
            }
            let count = await Store.countDocuments(options).exec()
            let page = req.body.page || 1
            let pageSize = 10 || count
            let data = await Store.find(options).skip((page - 1) * pageSize).limit(pageSize).sort({ index: 1 }).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取门店列表成功', result)
        } catch (e) {
            next(e)
        }
    },
    storeHomePage: async (req, res, next) => {
        try {
            let store = await Store.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            res.ok('获取门店详情成功', store)
        } catch (e) {
            next(e)
        }
    },
    storeRecommend: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            options.page = { $in: 'store' }
            let recommendation = await Recommendation.find(options).populate('product store').exec()
            res.ok('获取推荐成功', recommendation)
        } catch (e) {
            next(e)
        }
    },
    storeActivity: async (req, res, next) => {
        try {
            let activity = await Activity.find({ isDelete: 0 }).exec()
            res.ok('获取活动成功', activity)
        } catch (e) {
            next(e)
        }
    },
    couponList: async (req, res, next) => {
        try {
            let couponList = await Coupon.find({ isDelete: 0 }).exec()
            res.ok('获取优惠券成功', couponList)
        } catch (e) {
            next(e)
        }
    },
    pointProductList: async (req, res, next) => {
        try {
            let product = await Product.find({ isDelete: 0 }).exec()
            res.ok('获取商品成功', product)
        } catch (e) {
            next(e)
        }
    },
    nearbyStores: async (req, res, next) => {
        try {
            let limit = req.body.limit || 1
            let stores = await Store.find({ location: { $near: [req.body.latitude, req.body.longitude,] }, _id: { $ne: req.body.store }, isDelete: 0 }).limit(limit).exec()
            res.ok('门店获取成功', stores)
        } catch (e) {
            next(e)
        }
    },
    activityList: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            if (req.body.store) {
                options.store = req.body.store
            }
            let count = await Activity.countDocuments(options).exec()
            let page = req.body.page || 1
            let pageSize = 10 || count
            let data = await Activity.find(options).skip((page - 1) * pageSize).limit(pageSize).sort({ createdAt: -1 }).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取活动成功', result)
        } catch (e) {
            next(e)
        }
    },
    oneAactivity: async (req, res, next) => {
        try {
            let activity = await Activity.findOne({ _id: req.body.id, isDelete: 0 }).populate('store').exec()
            res.ok('获取活动详情成功', activity)
        } catch (e) {
            next(e)
        }
    },
    oneStore: async (req, res, next) => {
        try {
            let data = {}
            data.store = await Store.findOne({ _id: req.body.id, isDelete: 0 }).populate('recommendActivity').exec()
            if (data.store == null) {
                return res.ok('未查询到改门店')
            }
            data.dish = await Dish.find({ store: { $in: req.body.id }, isDelete: 0 }).exec()
            data.recommendActivity = data.store.recommendActivity.filter(e => e.isDelete ==0)
            res.ok('获取成功', data)
        } catch (e) {
            next(e)
        }
    },
    memberQR: async (req, res, next) => {
        try { //unionid fix
            let member = await Member.findOne({ unionID: req.body.unionid, isDelete: 0 }).exec()
            if (member.code == undefined) {
                let QRlink = "http://api.qrserver.com/v1/create-qr-code/?data=" + member.code + "&size=1000x1000"
                return res.ok('未领取会员卡，二维码为测试', QRlink)
            }
            let QRlink = "http://api.qrserver.com/v1/create-qr-code/?data=" + member.code + "&size=1000x1000"
            res.ok('会员二维码', QRlink)
        } catch (e) {
            next(e)
        }
    },
    mallRecommend: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            options.page = { $in: 'mall' }
            let data = await Recommendation.findOne(options).populate({
                path: 'detail.product',
                model: Product
            }).populate({
                path: 'detail.store',
                model: Store
            }).populate({
                path: 'detail.dish',
                model: Dish
            }).populate({
                path: 'detail.activity',
                model: Activity
            }).populate({
                path: 'detail.voucher',
                model: Voucher
            }).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || data.detail.length
            let start = (page - 1) * pageSize
            let end = page * pageSize
            let result = {}
            result.total = data.detail.length
            result.currentPage = page
            result.pageSize = pageSize
            result.data = data.detail.slice(start, end)
            res.ok('获取推荐成功', result)
        } catch (e) {
            next(e)
        }
    },
    mallAD: async (req, res, next) => {
        try {
            let count = await Advertisement.countDocuments({ isDelete: 0 }).exec()
            let index = getRandom(0, count)
            let advertisement = await Advertisement.findOne({ isDelete: 0 }).skip(index).exec()
            res.ok('获取广告成功', advertisement)
        } catch (e) {
            next(e)
        }
    },
    mallProductCategory: async (req, res, next) => {
        try {
            let productCategory = await ProductCategory.find({ isDelete: 0 }).exec()
            res.ok('商品种类获取成功', productCategory)
        } catch (e) {
            next(e)
        }
    },
    mallProductList: async (req, res, next) => {
        try {
            let productCategory = await ProductCategory.findOne({ _id: req.body.productCategory, isDelete: 0 }).exec()
            if (productCategory.name == '兑换券') {
                let option = {}
                option.isDelete = 0
                option.status = 1
                if (req.body.title) {
                    option.title = new RegExp(req.body.title, 'i')
                }
                if (req.body.store) {
                    option.store = { $in: req.body.store }
                }
                let count = await Voucher.countDocuments(option).exec()
                let page = req.body.page || 1
                let pageSize = req.body.pageSize || count
                let data = await Voucher.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
                let result = {}
                result.total = count
                result.currentPage = page
                result.data = data
                result.pageSize = pageSize
                res.ok('获取成功', result)
            } else {
                let option = {}
                option.isDelete = 0
                option.status = 1
                if (req.body.productCategory) {
                    option.productCategory = { $in: req.body.productCategory }
                }
                if (req.body.name) {
                    option.name = new RegExp(req.body.name, 'i')
                }
                let count = await Product.countDocuments(option).exec()
                let voucherCount = await Voucher.countDocuments(option).exec()
                let page = req.body.page || 1
                let pageSize = req.body.pageSize || count
                let data = await Product.find(option).skip((page - 1) * pageSize).limit(pageSize).populate('attribute').exec()
                let result = {}
                result.total = count + voucherCount
                result.currentPage = page
                result.data = data
                result.pageSize = pageSize
                if ((page * pageSize) > count) {
                    if (((page * pageSize) - count) < pageSize) {
                        let option = {}
                        option.isDelete = 0
                        option.status = 1
                        if (req.body.title) {
                            option.title = new RegExp(req.body.title, 'i')
                        }

                        if (req.body.store) {
                            option.store = { $in: req.body.store }
                        }
                        if (req.body.productCategory) {
                            option.productCategory = { $in: req.body.productCategory }
                        }
                        let voucherData = await Voucher.find(option).limit((page * pageSize) - count).exec()
                        result.data = result.data.concat(voucherData)
                        res.ok('获取成功', result)
                    } else {
                        let option = {}
                        option.isDelete = 0
                        option.status = 1
                        if (req.body.title) {
                            option.title = new RegExp(req.body.title, 'i')
                        }

                        if (req.body.store) {
                            option.store = { $in: req.body.store }
                        }
                        if (req.body.productCategory) {
                            option.productCategory = { $in: req.body.productCategory }
                        }
                        // let voucherCount = await Voucher.countDocuments(option).exec()
                        let page = req.body.page || 1
                        let pageSize = req.body.pageSize || voucherCount
                        let voucherData = await Voucher.find(option).skip(((page - 1) * pageSize) - count).limit(pageSize).exec()
                        let result = {}
                        result.total = count + voucherCount
                        result.currentPage = page
                        result.data = voucherData
                        result.pageSize = pageSize
                        res.ok('获取成功', result)
                    }
                } else {
                    res.ok('获取成功', result)
                }
            }
        } catch (e) {
            next(e)
        }
    },
    getAllRecommend: async (req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            let count = await Recommendation.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Recommendation.find(option).skip((page - 1) * pageSize).limit(pageSize).populate('product store').exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取推荐成功', result)
        } catch (e) {
            next(e)
        }
    },
    getOneRecommend: async (req, res, next) => {
        try {
            let recommendation = await Recommendation.findOne({ _id: req.body.id, isDelete: 0 }).populate('product store').exec()
            res.ok('获取推荐成功', recommendation)
        } catch (e) {
            next(e)
        }
    },
    oneProduct: async (req, res, next) => {
        try {
            let product = await Product.findOne({ _id: req.body.id, isDelete: 0 }).populate('productCategory attribute').exec()
            res.ok('获取商品成功', product)
        } catch (e) {
            next(e)
        }
    },
    isFavorited: async (req, res, next) => {
        try {
            let myFavorite = await MyFavorite.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            if (myFavorite == null) {
                let newMyFavorite = new MyFavorite({
                    product: [],
                    openid: req.body.openid,
                    unionID: req.body.unionid,
                    isDelete: 0
                })
                await newMyFavorite.save()
                res.ok("查询成功", { isFavorited: 0 })
            } else {
                let favoriteList = myFavorite.product
                let index = favoriteList.indexOf(req.body.product)
                if (index == -1) {
                    res.ok('查询成功', { isFavorited: 0 })
                } else {
                    res.ok('查询成功', { isFavorited: 1 })
                }
            }
        } catch (e) {
            next(e)
        }
    },
    addCart: async (req, res, next) => {
        try {
            if (req.body.productsub) {
                let cart = await Cart.findOne({ openid: req.body.openid }).exec()
                if (cart == null) {
                    let newCart = new Cart({
                        products: [{ product: req.body.productsub, amount: req.body.amount }],
                        openid: req.body.openid,
                        // unionID: req.body.unionid,
                        isDelete: 0
                    })
                    await newCart.save()
                    res.ok('添加购物车成功')
                } else {
                    let temp = cart.products.map(e => {
                        return e.product
                    })
                    // let index = cart.products.indexOf(req.body.id)
                    let index = temp.indexOf(req.body.productsub)
                    if (index == -1) {
                        cart.products.push({ product: req.body.productsub, amount: req.body.amount })
                        cart.markModified("products")
                        await cart.save()
                        res.ok('添加购物成功')
                    } else {
                        if (req.body.amount == 0) {
                            cart.products.splice(index, 1)
                            cart.markModified("products")
                            await cart.save()
                            res.ok('修改购物车成功')
                        } else {
                            cart.products[index].amount = req.body.amount
                            cart.markModified("products")
                            await cart.save()
                            res.ok('修改购物车成功')
                        }
                    }
                }
            } else {
                res.ok('请确认规格')
            }
        } catch (e) {
            next(e)
        }
    },
    deleteCart: async (req, res, next) => {
        try {
            let cart = await Cart.findOne({ openid: req.body.openid }).exec()
            let temp = cart.products.map(e => {
                return e.product
            })
            let index = temp.indexOf(req.body.id)
            if (index != -1) {
                cart.products.splice(index, 1)
                cart.markModified("products")
                await cart.save()
                res.ok('删除购物车成功')
            }
        } catch (e) {
            next(e)
        }
    },
    cartList: async (req, res, next) => {
        try {
            let cart = await Cart.findOne({ openid: req.body.openid }).populate({
                path: 'products.product',
                model: ProductSub,
                populate: { path: 'product' }
            }).exec()
            if (cart == null) {
                let newCart = new Cart({
                    products: [],
                    openid: req.body.openid,
                    // unionID: req.body.unionid,
                    isDelete: 0
                })
                await newCart.save()
                res.ok('查询收藏成功', newCart)
            } else {
                res.ok('查询收藏成功', cart)
            }
        } catch (e) {
            next(e)
        }
    },
    changeCartProduct: async (req, res, next) => {
        try {
            let cart = await Cart.findOne({ openid: req.body.openid }).exec()
            let temp = cart.products.map(e => {
                return e.product
            })
            let index = temp.indexOf(req.body.id)
            // let index = cart.product.indexOf(req.body.id)
            if (index != -1) {
                if (req.body.amount == 0) {
                    cart.products.splice(index, 1)
                    cart.markModified("products")
                    await cart.save()
                    res.ok('修改购物车成功')
                } else {
                    cart.products[index].amount = req.body.amount
                    cart.markModified("products")
                    await cart.save()
                    res.ok('修改购物车成功')
                }
            } else {
                if (req.body.amount != 0) {
                    cart.products.push({ product: req.body.id, amount: req.body.amount })
                    cart.markModified("products")
                    await cart.save()
                    res.ok('修改购物车成功')
                }
            }
        } catch (e) {
            next(e)
        }
    },
    deleteCartProduct: async (req, res, next) => {
        try {
            let cart = await Cart.findOne({ openid: req.body.openid }).exec()
            let temp = cart.products.map(e => {
                return e.product
            })
            let index = temp.indexOf(req.body.id)
            if (index != -1) {
                cart.products.splice(index, 1)
                cart.markModified("products")
                await cart.save()
                res.ok('删除购物车成功')
            }


            // let cart = await Cart.findOne({ unionID: req.body.unionid }).exec()
            // let index = cart.product.indexOf(req.body.id)
            // if (index != -1) {
            //     cart.products.splice(index, 1)
            //     cart.markModified("products")
            //     await cart.save()
            //     res.ok('修改购物车成功')
            // }
        } catch (e) {
            next(e)
        }
    },
    personalCenter: async (req, res, next) => {
        try {
            let unionID = req.body.unionid
            let member = await Member.findOne({ unionID: unionID }).exec()
            if (member.code == undefined || member.code == "") {
                member.code = ""
                return res.ok('未领取会员卡', member)
            }
            res.ok('获取个人信息成功', member)
        } catch (e) {
            next(e)
        }
    },
    myInfo: async (req, res, next) => {
        try {
            let openid = req.body.openid
            let user = await User.findOne({ openid: openid }).exec()
            // let member = await Member.findOne({ unionID: unionID }).exec()
            res.ok('获取个人信息成功', user)
        } catch (e) {
            next(e)
        }
    },
    getExpenseHistoryList: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            options.openid = req.body.openid
            let count = await ExpenseHistory.countDocuments(options).exec()
            let page = req.body.page || 1
            let pageSize = 10 || count
            let data = await ExpenseHistory.find(options).skip((page - 1) * pageSize).limit(pageSize).sort({ createdAt: -1 }).populate('store order member').exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取消费记录成功', result)
        } catch (e) {
            next(e)
        }
    },
    orderList: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            options.openid = req.body.openid
            if (!Validate.isEmpty(req.body.status)) {
                options.status = req.body.status
            }
            let count = await Order.countDocuments(options).exec()
            let page = req.body.page || 1
            let pageSize = 10 || count
            let data = await Order.find(options).skip((page - 1) * pageSize).limit(pageSize).sort({ createdAt: -1 }).populate({
                path: 'products.product',
                model: ProductSub,
                populate: { path: 'product' }
            }).populate({
                path: 'products.voucher',
                model: Voucher,
                populate: { path: 'voucher' }
            }).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取订单列表成功', result)
        } catch (e) {
            next(e)
        }
    },
    oneOrder: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.id, isDelete: 0 }).populate({
                path: 'products.product',
                model: ProductSub,
                populate: { path: 'product' }
            }).populate({
                path: 'products.voucher',
                model: Voucher
            }).populate({
                path: 'reimburse',
                model: Reimburse
            }).populate('address coupon')
                .exec()
            res.ok('获取订单成功', order)
        } catch (e) {
            next(e)
        }
    },
    submitOrder: async (req, res, next) => {
        try {


            // if(true){
            //     let checkStatus = 0
            //     let userPoint = await UserPoint.findOne({openid:req.body.openid,isDelete:0}).exec()
            //     if(userPoint == 1&&userPoint.current<amountOfUsePoint){
            //         return res.send({code:'201',msg:"积分余额不足"})
            //     }
            //     for(let i=0;i<req.body.products.length;i++){
            //         if(Object.keys(req.body.products[i])[0] == 'voucher'){
            //             let voucherId = req.body.products[i]['voucher']
            //             let amount = req.body.products[i]['amount']
            //             let voucher = await Voucher.findOne({_id:voucherId,isDelete:0}).exec()
            //             let myVoucherCount = await MyVoucher.countDocuments({openid:req.body.openid,voucher:voucherId}).exec()
            //             if((Number(amount)+myVoucherCount)>voucher.limit){
            //                 return checkStatus = 1
            //                 // return res.send({code:201,msg:'超过购买数量限制'})
            //             }
            //             if(Number(amount>voucher.currentCount)){
            //                 return checkStatus = 2
            //                 // return res.send({code:201,msg:'库存不足'})
            //             }
            //         }else if(Object.keys(req.body.products[i])[0] == 'product'){
            //             let stockNotEnough = false
            //                 let productSub = await ProductSub.findOne({ _id: req.body.products[i].product, isDelete: 0 }).exec()
            //                 productSub.stock -= req.body.products[i].amount
            //                 await productSub.save()
            //                 if(productSub.stock<0){
            //                     stockNotEnough = true
            //                 }
            //             if(stockNotEnough){
            //                     let productSub = await ProductSub.findOne({ _id: req.body.products[i].product, isDelete: 0 }).exec()
            //                     productSub.stock += req.body.products[i].amount
            //                     await productSub.save()
            //                     return checkStatus = 2
            //                     // return res.send({code:'201',msg:"库存不足"})
            //             }
            //         }
            //         if(checkStatus ===0){
            //             let addressID = ''
            //             let address = await Address.findOne({
            //                 userName:req.body.address.userName,
            //                 cityName:req.body.address.cityName,
            //                 countyName:req.body.address.countyName,
            //                 detailInfo:req.body.address.detailInfo,
            //                 telNumber:req.body.address.telNumber,
            //                 openid :req.body.openid,
            //                 isDelete:0}).exec()
            //             if(address==null){
            //                 let newAddress = new Address({
            //                     userName:req.body.address.userName,
            //                     postalCode:req.body.address.postalCode,
            //                     provinceName:req.body.address.provinceName,
            //                     cityName:req.body.address.cityName,
            //                     countyName:req.body.address.countyName,
            //                     detailInfo:req.body.address.detailInfo,
            //                     nationalCode:req.body.address.nationalCode,
            //                     telNumber:req.body.address.telNumber,
            //                     createdAt: new Date(),
            //                     updatedAt: new Date(),
            //                     openid :req.body.openid,
            //                     isDelete:0
            //                 })
            //                 await newAddress.save()
            //                 addressID = newAddress._id
            //             }else{
            //                 addressID = address._id
            //             }
            //             let newOrder = new Order({
            //                 unionID: req.body.unionid,
            //                 openid: req.body.openid,
            //                 products: req.body.products,
            //                 updatedAt: new Date(),
            //                 coupon: req.body.coupon,
            //                 total: req.body.total,
            //                 totalPoint: req.body.totalPoint,
            //                 status: 0, // 0代付款，1已付款，2退款，-1 过期,
            //                 isDelete: 0,
            //                 comment: req.body.comment, // 用户备注
            //                 usePoint:req.body.usePoint,
            //                 amountOfUsePoint:req.body.amountOfUsePoint,
            //                 type:0,
            //                 address:addressID
            //             })
            //             await newOrder.save()
            //             res.ok('订单创建成功', newOrder)
            //         }else if(checkStatus ===1){
            //             res.send({code:201,msg:'超过购买数量限制'})
            //         }else if(checkStatus ===2){
            //             res.send({code:'201',msg:"库存不足"})
            //         }
            //     }
            // }
            // return



            if (Object.keys(req.body.products[0])[0] == 'voucher') {
                let nowDate = new Date()
                let voucherId = req.body.products[0]['voucher']
                let amount = req.body.products[0]['amount']
                let voucher = await Voucher.findOne({ _id: voucherId, isDelete: 0 }).exec()
                let myVoucherCount = await MyVoucher.countDocuments({ openid: req.body.openid, voucher: voucherId }).exec()
                if ((Number(amount) + myVoucherCount) > voucher.limit) {
                    return res.send({ code: 201, msg: '超过购买数量限制' })
                }
                if (Number(amount > voucher.currentCount)) {
                    return res.send({ code: 201, msg: '库存不足' })
                }
                if (nowDate < voucher.buyStartDate) {
                    return res.send({ code: 201, msg: '未到开始购买时间' })
                }
                if (nowDate > voucher.buyExpireDate) {
                    return res.send({ code: 201, msg: '已超过购买期限' })
                }
                let newOrder = new Order({
                    unionID: req.body.unionid,
                    openid: req.body.openid,
                    products: [{ voucher: voucherId, amount: amount }], //// {product: productSubId,amount : 数字}
                    updatedAt: new Date(),
                    // total: voucher.discountPrice * amount, //总价
                    status: 0,
                    isDelete: 0,
                    type: 1,
                    total: req.body.total,
                    totalPoint: req.body.totalPoint,
                    comment: req.body.comment, // 用户备注
                    usePoint: req.body.usePoint,
                    amountOfUsePoint: req.body.amountOfUsePoint,
                    store:voucher.store
                })
                await newOrder.save()
                res.ok('提交成功', newOrder)
            } else if (Object.keys(req.body.products[0])[0] == 'product') {
                let userPoint = await UserPoint.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
                if (userPoint == 1 && userPoint.current < amountOfUsePoint) {
                    return res.send({ code: '201', msg: "积分余额不足" })
                }
                let stockNotEnough = false
                req.body.products.map(async e => {
                    let productSub = await ProductSub.findOne({ _id: e.product, isDelete: 0 }).exec()
                    productSub.stock -= e.amount
                    await productSub.save()
                    if (productSub.stock < 0) {
                        stockNotEnough = true
                    }
                })
                if (stockNotEnough) {
                    req.body.products.map(async e => {
                        let productSub = await ProductSub.findOne({ _id: e.product, isDelete: 0 }).exec()
                        productSub.stock += e.amount
                        await productSub.save()
                    })
                    return res.send({ code: '201', msg: "库存不足" })
                }
                let addressID = ''
                let address = await Address.findOne({
                    userName: req.body.address.userName,
                    cityName: req.body.address.cityName,
                    countyName: req.body.address.countyName,
                    detailInfo: req.body.address.detailInfo,
                    telNumber: req.body.address.telNumber,
                    openid: req.body.openid,
                    isDelete: 0
                }).exec()
                if (address == null) {
                    let newAddress = new Address({
                        userName: req.body.address.userName,
                        postalCode: req.body.address.postalCode,
                        provinceName: req.body.address.provinceName,
                        cityName: req.body.address.cityName,
                        countyName: req.body.address.countyName,
                        detailInfo: req.body.address.detailInfo,
                        nationalCode: req.body.address.nationalCode,
                        telNumber: req.body.address.telNumber,
                        createdAt: new Date(),
                        updatedAt: new Date(),
                        openid: req.body.openid,
                        isDelete: 0
                    })
                    await newAddress.save()
                    addressID = newAddress._id
                } else {
                    addressID = address._id
                }
                let newOrder = new Order({
                    unionID: req.body.unionid,
                    openid: req.body.openid,
                    products: req.body.products,
                    updatedAt: new Date(),
                    coupon: req.body.coupon,
                    total: req.body.total,
                    totalPoint: req.body.totalPoint,
                    status: 0, // 0代付款，1已付款，2退款，-1 过期,
                    isDelete: 0,
                    comment: req.body.comment, // 用户备注
                    usePoint: req.body.usePoint,
                    amountOfUsePoint: req.body.amountOfUsePoint,
                    type: 0,
                    address: addressID
                })
                await newOrder.save()
                res.ok('订单创建成功', newOrder)
            }

        } catch (e) {
            next(e)
        }
    },
    payOrder: async (req, res, next) => {
        try {
            const openid = req.body.openid
            const unionid = req.body.unionid
            var params = wxpay.generateParam(openid, req.body.orderId, parseInt(req.body.price * 100), 'test', req.body.type == undefined ? 0 : 1)

            var xml = params[0]
            var theparams = params[1]
            wxpay.wxPay(xml, function (err, response, body) {
                console.log(body, 'jbob')
                if ((body.return_code[0] == 'SUCCESS') && (body.result_code[0] == 'SUCCESS')) {
                    var payParams = wxpay.payParam(body)
                    res.send({ 'code': 200, 'data': payParams })
                } else if ((body.return_code[0] == 'SUCCESS') && (body.result_code[0] == 'FAIL')) {
                    console.log('payproblem', body)
                    if (body.err_code[0] == 'ORDERPAID') {

                        res.send({ 'code': 201 })
                    } else if (body.err_code[0] == 'OUT_TRADE_NO_USED') {
                        res.ok('订单号已使用')
                    } else {
                        res.send({ 'code': 400, msg: body.err_code, type: 'xxx' })
                    }

                } else {
                    res.send({ 'code': 400, msg: body, type: '111' })
                }

            })
        } catch (e) {
            next(e)
        }
    },
    confirmPaPyment: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            order.status = 1
            await order.save()
            let user = await User.findOne({ unionid: req.body.unionid, isDelete: 0 }).exec()
            let rate = user.vip == 0 ? 10 : 15
            let newExpenseHistory = new ExpenseHistory({
                openid: user.openid,
                unionID: user.unionID,
                cellphone: user.cellphone,
                store: order.store,
                order: order._id,
                updatedAt: new Date(),
                isDelete: 0,
                amount: order.total, // 价格
                memo: order.memo, //人工操作备注
                rate: rate, //10为10%
            })
            await newExpenseHistory.save()
            let newPointHistory = new PointHistory({
                openid: user.openid,
                unionID: user.unionID,
                order: order._id,
                expenseHistory: newExpenseHistory._id,
                expenseDate: new Date(),
                memo: newExpenseHistory.memo, //人工操作备注
                manual: 0, // 1位人工，0为自动
                amount: order.total * rate / 100, // 变动的积分数量
                type: 0, // 0 为加，1为减
                isDelete: 0,
            })
            await newPointHistory.save()
            res.ok('支付确认成功')
        } catch (e) {
            next(e)
        }
    },

    addFavorite: async (req, res, next) => {
        try {
            let myFavorite = await MyFavorite.findOne({ unionID: req.body.unionid }).exec()
            if (myFavorite == null) {
                let newMyFavorite = new MyFavorite({
                    product: req.body.id,
                    openid: req.body.openid,
                    unionID: req.body.unionid,
                    isDelete: 0
                })
                await newMyFavorite.save()
                res.ok('添加收藏成功')
            } else {
                let index = myFavorite.product.indexOf(req.body.id)
                if (index == -1) {
                    myFavorite.product.push(req.body.id)
                    myFavorite.markModified("product")
                    await myFavorite.save()
                    res.ok('添加收藏成功')
                } else {
                    res.ok('已收藏')
                }
            }
        } catch (e) {
            next(e)
        }
    },
    deleteFavorite: async (req, res, next) => {
        try {
            let myFavorite = await MyFavorite.findOne({ unionID: req.body.unionid }).exec()
            let index = myFavorite.product.indexOf(req.body.id)
            if (index != -1) {
                myFavorite.product.splice(index, 1)
                myFavorite.markModified("product")
                await myFavorite.save()
                res.ok('删除收藏成功')
            }
        } catch (e) {
            next(e)
        }
    },
    getUserFavorite: async (req, res, next) => {
        try {
            let myFavorite = await MyFavorite.findOne({ unionID: req.body.unionid }).populate('product').exec()
            if (myFavorite == null) {
                let newMyFavorite = new MyFavorite({
                    product: [],
                    openid: req.body.openid,
                    unionID: req.body.unionid,
                    isDelete: 0
                })
                await newMyFavorite.save()
                res.ok('查询收藏成功', newMyFavorite)
            } else {
                let page = req.body.page || 1
                let pageSize = req.body.pageSize || myFavorite.product.length
                let start = (page - 1) * pageSize
                let end = page * pageSize
                let result = {}
                result.total = myFavorite.product.length
                result.currentPage = page
                result.pageSize = pageSize
                result.data = myFavorite.product.slice(start, end)
                res.ok('查询收藏成功', result)
            }
        } catch (e) {
            next(e)
        }
    },
    getMemberCardExt: async (req, res, next) => {
        try {
            let memberCard = await MemberCard.findOne({ isDelete: 0 }, 'cardId').exec()
            let cardId = memberCard.cardId
            let timestamp = Date.parse(new Date()) / 1000
            let nonce_str = randomString()
            wxPublicAccessToken.cardTicket(function (token) {
                // console.log(timestamp, token, nonce_str, cardId)
                let temp = []
                temp.push(String(timestamp))
                temp.push(token)
                temp.push(nonce_str)
                temp.push(cardId)
                let dictSort = temp.sort()
                let signatureStr = dictSort.join('')
                let signature = sha1(signatureStr)
                let data = {}
                data.cardId = cardId
                data.timestamp = timestamp
                data.signature = signature
                data.nonce_str = nonce_str
                console.log(req.body.openid,data)
                res.ok('获取成功', data)
            })
        } catch (e) {
            next(e)
        }
    },
    addCardFail:async(req,res,next)=>{
        try {
            let openid = req.body.openid
            let failmsg = req.body.failmessage
            let data = req.body.data
            console.log(openid,failmsg,data)
            res.ok("错误信息")
        } catch (e) {
            next(e)
        }
    },
    addMemberCard:async (req, res, next) => {
        try {
            let user = User.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            // let member = Member.findOne({unionID:req.body.unionid,isDelete:0}).exec()
            // let userPoint = UserPoint.findOne({unionID:req.body.unionid,isDelete:0}).exec()

            //无积分赠送

            wxPublicAccessToken.getAccessToken(function (token) {
                let wxurl = "https://api.weixin.qq.com/card/code/decrypt?access_token=" + token
                let postdata = {
                    "encrypt_code": req.body.code
                }
                request({
                    url: wxurl,
                    method: "POST",
                    timeout: 10000,
                    body: postdata,
                    followRedirect: true,
                    json: true,
                    maxRedirects: 10
                }, async function (error, response, body) {
                    console.log(error, body, 'dd')
                    if(body.errcode=="40075"){
                        console.log(postdata,"errordata")
                    }
                    if (!error) {
                        let code = body.code
                        let member = await Member.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
                        if (member.code !== "" && member.code !== undefined) {
                            return res.send({ code: 201, msg: "已领取会员卡" })
                        }
                        if (member == null) {
                            let newmember = new Member({
                                openid: req.body.openid,
                                unionID: req.body.unionid,
                                code: code,
                                point: 0,
                                updatedAt: new Date(),
                                type: "普通会员",
                                isDelete: 0,
                            })
                            await newmember.save()
                        } else {
                            member.code = code
                            if (member.point) {
                                member.point = Number(member.point)
                            } else {
                                member.point = 0
                            }
                            if (Number(member.point) >= 1000) {
                                member.type = "VIP会员"
                                user.vip = 1
                                await user.save()
                            } else {
                                member.type = "普通会员"
                            }
                            member.updatedAt = new Date()
                            await member.save()
                        }
                        let userPoint = await UserPoint.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
                        if (userPoint == null) {
                            let newUserPoint = new UserPoint({
                                openid: req.body.openid,
                                unionID: req.body.unionid,
                                cellphone: user.cellphone,
                                updatedAt: new Date(),
                                total: 0, //总积分
                                current: 0, //现积分
                                pendingPoint: 0,
                                isDelete: 0,
                            })
                            await newUserPoint.save()
                        } else {
                            userPoint.updatedAt = new Date(),
                                userPoint.total = userPoint.total
                            userPoint.current = userPoint.current
                            await userPoint.save()
                        }
                        // let newcomerGift = await NewcomerGift.findOne({ isDelete: 0 }).exec()
                        // newcomerGift.gift.forEach(async e => {
                        //     let newOrder = new Order({
                        //         unionID: req.body.unionid,
                        //         openid: req.body.openid,
                        //         products: [{ voucher: e.id, amount: 1 }], //// {product: productSubId,amount : 数字}
                        //         updatedAt: new Date(),
                        //         status: 1,
                        //         isDelete: 0,
                        //         type: 1,
                        //         total: 0, //总价
                        //         totalPoint: 0, //积分总价
                        //     })
                        //     await newOrder.save()
                        //     if (e.type == "voucher") {
                        //         let newMyVoucher = new MyVoucher({
                        //             openid: req.body.openid,
                        //             unionID: req.body.unionid,
                        //             voucher: e.id,
                        //             amount: 1,
                        //             status: 0,//0未使用，1使用
                        //             updatedAt: new Date(),
                        //             order: newOrder._id,
                        //             isDelete: 0
                        //         })
                        //         await newMyVoucher.save()
                        //     }
                        // });
                        // let newPointHistory = new PointHistory({
                        //     openid: req.body.openid,
                        //     unionID: req.body.unionid,
                        //     expenseDate: new Date(),
                        //     manual: 0, // 1位人工，0为自动
                        //     amount: 100, // 变动的积分数量
                        //     type: 0, // 0 为加，1为减
                        //     isDelete: 0,
                        // })
                        // await newPointHistory.save()
                        if (user.referrer) {
                            let referrer = await User.findOne({ _id: user.referrer, isDelete: 0 }).exec()
                            let referrerPoint = await UserPoint.findOne({ openid: referrer.openid, isDelete: 0 }).exec()
                            referrerPoint.total = referrerPoint.total + 50
                            referrerPoint.current = referrerPoint.current + 50
                            await referrerPoint.save()
                            let referrerMember = await Member.findOne({ openid: referrer.openid, isDelete: 0 }).exec()
                            referrerMember.point = referrerMember.point + 50
                            await referrerMember.save()
                            let newPointHistory = new PointHistory({
                                openid: referrer.openid,
                                unionID: referrer.unionID,
                                expenseDate: new Date(),
                                manual: 0, // 1位人工，0为自动
                                amount: 50, // 变动的积分数量
                                type: 0, // 0 为加，1为减
                                isDelete: 0,
                            })
                            await newPointHistory.save()
                            wxPublicAccessToken.getAccessToken(function (token) {
                                request({
                                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                                    method: "POST",
                                    timeout: 10000,
                                    encoding: null,
                                    json: {
                                        "code": referrerMember.code,
                                        "card_id": memberCardNumber,
                                        "bonus": referrerMember.point
                                    }
                                }, function (error, response, body) {
                                    console.log(error)
                                })
                            })
                        }
                        wxPublicAccessToken.getAccessToken(function (token) {
                            request({
                                url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                                method: "POST",
                                timeout: 10000,
                                encoding: null,
                                json: {
                                    "code": member.code,
                                    "card_id": memberCardNumber,
                                    "bonus": member.point
                                }
                            }, function (error, response, body) {
                                console.log(error)
                                res.ok('会员卡领取成功')
                            })
                        })
                    }
                })
            })







            //有100积分赠送

            // wxPublicAccessToken.getAccessToken(function (token) {
            //     let wxurl = "https://api.weixin.qq.com/card/code/decrypt?access_token=" + token
            //     let postdata = {
            //         "encrypt_code": req.body.code
            //     }
            //     request({
            //         url: wxurl,
            //         method: "POST",
            //         timeout: 10000,
            //         body: postdata,
            //         followRedirect: true,
            //         json: true,
            //         maxRedirects: 10
            //     }, async function (error, response, body) {
            //         console.log(error, body, 'dd')
            //         if (!error) {
            //             let code = body.code
            //             let member = await Member.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            //             if(member.code !== ""){
            //                 return res.send({code:201,msg:"已领取会员卡"})
            //             }
            //             if (member == null) {
            //                 let newmember = new Member({
            //                     openid: req.body.openid,
            //                     unionID: req.body.unionid,
            //                     code: code,
            //                     point: 100,
            //                     updatedAt: new Date(),
            //                     type: "普通会员",
            //                     isDelete: 0,
            //                 })
            //                 await newmember.save()
            //             } else {
            //                 member.code = code
            //                 if (member.point) {
            //                     member.point = Number(member.point) + 100
            //                 } else {
            //                     member.point = 100
            //                 }
            //                 if (Number(member.point) >= 1000) {
            //                     member.type = "VIP会员"
            //                     user.vip = 1
            //                     await user.save()
            //                 } else {
            //                     member.type = "普通会员"
            //                 }
            //                 member.updatedAt = new Date()
            //                 await member.save()
            //             }
            //             let userPoint = await UserPoint.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            //             if (userPoint == null) {
            //                 let newUserPoint = new UserPoint({
            //                     openid: req.body.openid,
            //                     unionID: req.body.unionid,
            //                     cellphone: user.cellphone,
            //                     updatedAt: new Date(),
            //                     total: 0, //总积分
            //                     current: 100, //现积分
            //                     pendingPoint: 0,
            //                     isDelete: 0,
            //                 })
            //                 await newUserPoint.save()
            //             } else {
            //                 userPoint.updatedAt = new Date(),
            //                     userPoint.total = userPoint.total
            //                 userPoint.current = userPoint.current + 100
            //                 await userPoint.save()
            //             }
            //             let newPointHistory = new PointHistory({
            //                 openid: req.body.openid,
            //                 unionID: req.body.unionid,
            //                 expenseDate: new Date(),
            //                 manual: 0, // 1位人工，0为自动
            //                 amount: 100, // 变动的积分数量
            //                 type: 0, // 0 为加，1为减
            //                 isDelete: 0,
            //             })
            //             await newPointHistory.save()
            //             if (user.referrer) {
            //                 let referrer = await User.findOne({ _id: user.referrer, isDelete: 0 }).exec()
            //                 let referrerPoint = await UserPoint.findOne({ openid: referrer.openid, isDelete: 0 }).exec()
            //                 referrerPoint.total = referrerPoint.total + 50
            //                 referrerPoint.current = referrerPoint.current + 50
            //                 await referrerPoint.save()
            //                 let referrerMember = await Member.findOne({ openid: referrer.openid, isDelete: 0 }).exec()
            //                 referrerMember.point = referrerMember.point + 50
            //                 await referrerMember.save()
            //                 let newPointHistory = new PointHistory({
            //                     openid: referrer.openid,
            //                     unionID: referrer.unionID,
            //                     expenseDate: new Date(),
            //                     manual: 0, // 1位人工，0为自动
            //                     amount: 50, // 变动的积分数量
            //                     type: 0, // 0 为加，1为减
            //                     isDelete: 0,
            //                 })
            //                 await newPointHistory.save()
            //                 wxPublicAccessToken.getAccessToken(function (token) {
            //                     request({
            //                         url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
            //                         method: "POST",
            //                         timeout: 10000,
            //                         encoding: null,
            //                         json: {
            //                             "code": referrerMember.code,
            //                             "card_id": memberCardNumber,
            //                             "bonus": referrerMember.point
            //                         }
            //                     }, function (error, response, body) {
            //                         console.log(error)
            //                     })
            //                 })
            //             }
            //             wxPublicAccessToken.getAccessToken(function (token) {
            //                 request({
            //                     url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
            //                     method: "POST",
            //                     timeout: 10000,
            //                     encoding: null,
            //                     json: {
            //                         "code": member.code,
            //                         "card_id": memberCardNumber,
            //                         "bonus": member.point
            //                     }
            //                 }, function (error, response, body) {
            //                     console.log(error)
            //                     res.ok('会员卡领取成功')
            //                 })
            //             })
            //         }
            //     })
            // })
        } catch (e) {
            next(e)
        }
    },
    getMemberCode: async (req, res, next) => {
        try {
            let member = await Member.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            let user = await User.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            let totalPoint = 0
            if (userPoint == null) {
                if (member) {
                    let newUserPoint = new UserPoint({
                        openid: req.body.openid,
                        unionID: req.body.unionid,
                        updatedAt: new Date(),
                        total: 0, //总积分
                        current: member.point, //现积分
                        pendingPoint: 0,
                        isDelete: 0,
                    })
                    await newUserPoint.save()
                } else {
                    let newUserPoint = new UserPoint({
                        openid: req.body.openid,
                        unionID: req.body.unionid,
                        updatedAt: new Date(),
                        total: 0, //总积分
                        current: 0, //现积分
                        pendingPoint: 0,
                        isDelete: 0,
                    })
                    await newUserPoint.save()
                }
                totalPoint = 0
            } else {
                totalPoint = userPoint.total
            }
            let memberCard = await MemberCard.findOne({ isDelete: 0 }).exec()
            if (member == null) {
                let newMember = new Member({
                    openid: req.body.openid,
                    unionID: req.body.unionid,
                    code: "",
                    updatedAt: new Date(),
                    isDelete: 0,
                })
                await newMember.save()
                // newMember.code = null
                res.ok('未领取会员卡', newMember)
            } else if (member.code == "") {
                // member.code = null
                res.ok('未领取会员卡', member)
            } else {
                let data = {}
                data.member = member
                data.cardId = memberCard.cardId
                data.totalPoint = totalPoint
                if (userPoint) {
                    data.pendingPoint = userPoint.pendingPoint
                } else {
                    data.pendingPoint = 0
                }
                data.nextLevel = "10000"
                if (user.vip && user.vip == 1) {
                    data.nextLevel = "-"
                }
                res.ok('查询会员卡号成功', data)
            }
        } catch (e) {
            next(e)
        }
    },

    homePageActivity: async (req, res, next) => {
        try {
            let limit = req.body.limit || 1
            let showActivity = await ShowActivity.findOne({ isDelete: 0 }).populate('activity').exec()
            let activity = showActivity.activity.slice(0, limit)
            res.ok('获取成功', activity)
        } catch (e) {
            next(e)
        }
    },

    getDishList: async (req, res, next) => {
        try {
            let options = {}
            options.isDelete = 0
            if (req.body.store) {
                options.store = { $in: req.body.store }
            }
            let count = await Dish.countDocuments(options).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Dish.find(options).skip((page - 1) * pageSize).limit(pageSize).sort({ createdAt: -1 }).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取菜品成功', result)
        } catch (e) {
            next(e)
        }
    },


    getOneDish: async (req, res, next) => {
        try {
            let dish = await Dish.findOne({ _id: req.body.id, isDelete: 0 }).populate('store').exec()
            res.ok('获取菜品成功', dish)
        } catch (e) {
            next(e)
        }
    },
    isStaff: async (req, res, next) => {
        try {
            let staff = await Staff.findOne({ openid: req.body.openid, isDelete: 0 }).populate('store').exec()
            if (staff == null) {
                let user = await User.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
                if (user.cellphone) {
                    let staff = await Staff.findOne({ cellphone: user.cellphone, isDelete: 0 }).exec()
                    if (staff == null) {
                        res.ok('未查询到该员工')
                    } else {
                        staff.openid = req.body.openid
                        staff.unionID = req.body.unionid
                        await staff.save()
                        res.ok('查询成功', staff)
                    }
                } else {
                    res.ok('未查询到该员工')
                }
            } else {
                res.ok('查询成功', staff)
            }
        } catch (e) {
            next(e)
        }
    },
    addExpense: async (req, res, next) => {
        try {
            if (Validate.isEmpty(req.body.cellphone)) {
                return res.send({ code: 201, msg: '手机号有误' })
            }
            if (!req.body.amount) {
                return res.send({ code: 201, msg: "消费金额未填写" })
            }
            let staff = await Staff.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let user = await User.findOne({ cellphone: req.body.cellphone, isDelete: 0 }).exec()
            let store = await Store.findOne({ _id: req.body.store, isDelete: 0 }).exec()
            let member = await Member.findOne({ openid: user.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: user.openid, isDelete: 0 }).exec()
            let payPrice = Number(req.body.amount)
            let point = Number(req.body.point)
            if (req.body.usePoint == 1) {
                if (point > userPoint.current) {
                    return res.send({ code: 201, msg: '积分不足' })
                }
                if (payPrice < point) {
                    return res.send({ code: 201, msg: '使用积分大于消费金额' })
                }
                payPrice = payPrice - point
            }
            let changePoint = Math.round(payPrice * store.attribute / 100)
            let attribute = store.attribute
            if (user.vip == 1) {
                changePoint = Math.round(payPrice * store.attributeVIP / 100)
                attribute = store.attributeVIP
            }
            if (req.body.notGivePoint == 1) {
                changePoint = 0
            }
            let newExpenseHistory = new ExpenseHistory({
                openid: user.openid,
                unionID: user.unionID,
                cellphone: user.cellphone,
                store: req.body.store,
                member: member._id,
                staff: staff._id,
                updatedAt: new Date(),
                isDelete: 0,
                usePoint: req.body.usePoint, //0不使用，1使用
                amount: req.body.amount, // 价格（未抵扣积分）
                payPrice: payPrice, //支付价格（抵扣积分后）
                point: point,
                earnPoints: changePoint,
                pendingPoint: changePoint,
                memo: req.body.memo, //人工操作备注
                rate: attribute, //10为10%
                givePoint: req.body.givePoint,
                verify: 0,
                review: 0,
                billNumber: req.body.billNumber,
                billImage: req.body.billImage
            })
            await newExpenseHistory.save()
            if (changePoint > 0) {
                if (userPoint.pendingPoint == undefined) {
                    userPoint.pendingPoint = changePoint
                } else {
                    userPoint.pendingPoint = userPoint.pendingPoint + changePoint
                }
                userPoint.updatedAt = new Date()
                await userPoint.save()
            }
            if (req.body.usePoint == 1) {
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    member: member._id,
                    expenseHistory: newExpenseHistory._id,
                    expenseDate: newExpenseHistory.updatedAt,
                    manual: 0, // 1位人工，0为自动
                    amount: point, // 变动的积分数量
                    type: 1, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                member.point = member.point - point
                member.updatedAt = new Date()
                await member.save()
                userPoint.current = userPoint.current - point
                userPoint.updatedAt = new Date()
                await userPoint.save()
                wxPublicAccessToken.getAccessToken(function (token) {
                    request({
                        url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                        method: "POST",
                        timeout: 10000,
                        encoding: null,
                        json: {
                            "code": member.code,
                            "card_id": memberCardNumber,
                            "bonus": member.point
                        }
                    }, function (error, response, body) {
                        console.log(error)
                        res.ok('添加消费记录完成')
                    })
                })
            } else {
                res.ok('添加消费记录完成')
            }
            // if(changePoint>0 && req.body.givePoint==1){
            //     let newPointHistory = new PointHistory({
            //         openid: user.openid,
            //         unionID: user.unionID,
            //         member: member._id,
            //         expenseHistory: newExpenseHistory._id,
            //         expenseDate: newExpenseHistory.updatedAt,
            //         manual: 0, // 1位人工，0为自动
            //         amount: changePoint, // 变动的积分数量
            //         type: 0, // 0 为加，1为减
            //         isDelete: 0,
            //     })
            //     await newPointHistory.save()
            //     member.point = member.point + changePoint
            //     member.updatedAt = new Date()
            //     await member.save()
            //     userPoint.total = userPoint.total + changePoint
            //     if(userPoint.total>=10000){
            //         user.vip = 1
            //         member.type = "VIP会员"
            //         await user.save()
            //         await member.save()
            //     }
            //     userPoint.current = userPoint.current + changePoint
            //     userPoint.updatedAt = new Date()
            //     await userPoint.save()
            //     wxPublicAccessToken.getAccessToken(function(token) {
            //         request({
            //                  url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
            //                  method: "POST",
            //                  timeout: 10000,
            //                  encoding: null,
            //                  json:{
            //                     "code": member.code,
            //                     "card_id": memberCardNumber,
            //                     "bonus": member.point
            //                  }
            //              },function(error, response, body){
            //                 console.log(error)
            //                 res.ok('添加消费记录完成')
            //         })
            //     })
            // }else{
            //     res.ok('添加消费记录完成')
            // }
            // res.ok('微信会员卡积分未完成')
        } catch (e) {
            next(e)
        }
    },
    addExpenseNotGivePoint: async (req, res, next) => {
        try {
            if (Validate.isEmpty(req.body.cellphone)) {
                return res.send({ code: 201, msg: '手机号有误' })
            }
            if (!req.body.amount) {
                return res.send({ code: 201, msg: "消费金额未填写" })
            }
            let staff = await Staff.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let user = await User.findOne({ cellphone: req.body.cellphone, isDelete: 0 }).exec()
            let store = await Store.findOne({ _id: req.body.store, isDelete: 0 }).exec()
            let member = await Member.findOne({ openid: user.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: user.openid, isDelete: 0 }).exec()
            let payPrice = Number(req.body.amount)
            let point = Number(req.body.point)
            if (req.body.usePoint == 1) {
                if (point > userPoint.current) {
                    return res.send({ code: 201, msg: '积分不足' })
                }
                if (payPrice < point) {
                    return res.send({ code: 201, msg: '使用积分大于消费金额' })
                }
                payPrice = payPrice - point
            }
            let changePoint = 0
            let attribute = store.attribute
            if (user.vip == 1) {
                attribute = store.attributeVIP
            }
            let newExpenseHistory = new ExpenseHistory({
                openid: user.openid,
                unionID: user.unionID,
                cellphone: user.cellphone,
                store: req.body.store,
                member: member._id,
                staff: staff._id,
                updatedAt: new Date(),
                isDelete: 0,
                usePoint: req.body.usePoint, //0不使用，1使用
                amount: req.body.amount, // 价格（未抵扣积分）
                payPrice: payPrice, //支付价格（抵扣积分后）
                point: point,
                earnPoints: changePoint,
                pendingPoint: changePoint,
                memo: req.body.memo, //人工操作备注
                rate: attribute, //10为10%
                givePoint: req.body.givePoint,
                verify: 0,
                review: 0,
                billNumber: req.body.billNumber,
                billImage: req.body.billImage
            })
            await newExpenseHistory.save()
            if (changePoint > 0) {
                if (userPoint.pendingPoint == undefined) {
                    userPoint.pendingPoint = changePoint
                } else {
                    userPoint.pendingPoint = userPoint.pendingPoint + changePoint
                }
                userPoint.updatedAt = new Date()
                await userPoint.save()
            }
            if (req.body.usePoint == 1) {
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    member: member._id,
                    expenseHistory: newExpenseHistory._id,
                    expenseDate: newExpenseHistory.updatedAt,
                    manual: 0, // 1位人工，0为自动
                    amount: point, // 变动的积分数量
                    type: 1, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                member.point = member.point - point
                member.updatedAt = new Date()
                await member.save()
                userPoint.current = userPoint.current - point
                userPoint.updatedAt = new Date()
                await userPoint.save()
                wxPublicAccessToken.getAccessToken(function (token) {
                    request({
                        url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                        method: "POST",
                        timeout: 10000,
                        encoding: null,
                        json: {
                            "code": member.code,
                            "card_id": memberCardNumber,
                            "bonus": member.point
                        }
                    }, function (error, response, body) {
                        console.log(error)
                        res.ok('添加消费记录完成')
                    })
                })
            } else {
                res.ok('添加消费记录完成')
            }
        } catch (e) {
            next(e)
        }
    },
    getStaffExpenseHistoryList: async (req, res, next) => {
        try {
            let staff = await Staff.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            let option = {}
            option.isDelete = 0
            option.staff = staff._id
            let count = await ExpenseHistory.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await ExpenseHistory.find(option).skip((page - 1) * pageSize).limit(pageSize).populate('order store member').sort({ createdAt: -1 }).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            return res.ok('获取消费记录成功', result)
        } catch (e) {
            next(e)
        }
    },
    recallUserExpenseHistory: async (req, res, next) => {
        try {
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            expenseHistory.isDelete = 1
            await expenseHistory.save()
            let user = await User.findOne({ unionID: expenseHistory.unionID, isDelete: 0 }).exec()
            let member = await Member.findOne({ unionID: expenseHistory.unionID, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ unionID: expenseHistory.unionID, isDelete: 0 }).exec()
            if (expenseHistory.usePoint == 1) {
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    member: member._id,
                    expenseHistory: expenseHistory._id,
                    expenseDate: expenseHistory.updatedAt,
                    manual: 0, // 1位人工，0为自动
                    amount: expenseHistory.point, // 变动的积分数量
                    type: 0, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                member.point = member.point + expenseHistory.point
                member.updatedAt = new Date()
                await member.save()
                userPoint.current = userPoint.current + expenseHistory.point
                userPoint.updatedAt = new Date()
                await userPoint.save()
            }
            if (expenseHistory.earnPoints > 0) {
                let newPointHistory = new PointHistory({
                    openid: user.openid,
                    unionID: user.unionID,
                    member: member._id,
                    expenseHistory: expenseHistory._id,
                    expenseDate: expenseHistory.updatedAt,
                    manual: 0, // 1位人工，0为自动
                    amount: expenseHistory.earnPoints, // 变动的积分数量
                    type: 1, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                member.point = member.point - expenseHistory.earnPoints
                member.updatedAt = new Date()
                await member.save()
                userPoint.total = userPoint.total - expenseHistory.earnPoints
                userPoint.current = userPoint.current - expenseHistory.earnPoints
                userPoint.updatedAt = new Date()
                await userPoint.save()
            }
            wxPublicAccessToken.getAccessToken(function (token) {
                request({
                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                    method: "POST",
                    timeout: 10000,
                    encoding: null,
                    json: {
                        "code": member.code,
                        "card_id": memberCardNumber,
                        "bonus": member.point
                    }
                }, function (error, response, body) {
                    console.log(error)
                    res.ok('撤销消费记录完成')
                })
            })
            // res.ok('微信会员卡积分未完成')
        } catch (e) {
            next(e)
        }
    },
    searchUserByQR: async (req, res, next) => {
        try {
            let member = await Member.findOne({ code: req.body.code, isDelete: 0 }).exec()
            if (member == null || member.code == "") {
                return res.sned({ code: 201, msg: '未查询到用户' })
            }
            let user = await User.findOne({ openid: member.openid }).exec()
            let userPoint = await UserPoint.findOne({ openid: member.openid }).exec()
            let result = {}
            result.name = user.name
            result.cellphone = user.cellphone
            result.current = userPoint.current
            result.pendingPoint = userPoint.pendingPoint
            res.ok('查找用户成功', result)
        } catch (e) {
            next(e)
        }
    },
    hasInformation: async (req, res, next) => {
        try {
            let user = await User.findOne({ openid: req.body.openid, isDelete: 0 }, 'cellphone name birthday email').exec()
            if (user == null || !user.name || !user.birthday || !user.cellphone) {
                res.ok('查询成功', { hasInformation: 0, user: user })
            } else {
                res.ok('查询成功', { hasInformation: 1, user: user })
            }
        } catch (e) {
            next(e)
        }
    },
    submitInformation: async (req, res, next) => {
        try {
            let user = await User.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            user.name = req.body.name
            if (req.body.birthday) {
                let birthday = (Number(req.body.birthday[0]) + 1) + "-" + (Number(req.body.birthday[1]) + 1)
                user.birthday = new Date(birthday)
            }
            user.cellphone = req.body.cellphone
            user.email = req.body.email
            user.updatedAt = new Date()
            await user.save()
            let member = await Member.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            if (member != null) {
                let userPoint = await UserPoint.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
                if (userPoint == null) {
                    let newUserPoint = new UserPoint({
                        openid: req.body.openid,
                        unionID: req.body.unionid,
                        cellphone: user.cellphone,
                        updatedAt: new Date(),
                        total: 0, //总积分
                        current: member.point, //现积分
                        pendingPoint: 0,
                        isDelete: 0,
                    })
                    await newUserPoint.save()
                }
            }
            res.ok('提交信息成功', user)
        } catch (e) {
            next(e)
        }
    },
    changeUserInfo: async (req, res, next) => {
        try {
            let user = await User.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            if (req.body.name) {
                user.name = req.body.name
            }
            if (req.body.birthday) {
                let birthday = (Number(req.body.birthday[0]) + 1) + "-" + (Number(req.body.birthday[1]) + 1)
                user.birthday = new Date(birthday)
            }
            if (req.body.email) {
                user.email = req.body.email
            }
            if (req.body.cellphone) {
                user.cellphone = req.body.cellphone
            }
            user.updatedAt = new Date()
            await user.save()
            res.ok('信息修改成功', user)
        } catch (e) {
            next(e)
        }
    },
    getRules: async (req, res, next) => {
        try {
            let rules = await Rules.findOne({ isDelete: 0 }).exec()
            return res.ok('查询规则成功', rules)
        } catch (e) {
            next(e)
        }
    },
    addReferrer: async (req, res, next) => {
        try {
            req.body
            let user = await User.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            user.referrer = req.body.referrer
            await user.save()
            return res.ok('推荐人添加成功', user)
        } catch (e) {
            next(e)
        }
    },
    pathSource: async (req, res, next) => {
        try {
            let user = await User.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            user.way = req.body.way
            await user.save()
            return res.ok('来源添加成功', user)
        } catch (e) {
            next(e)
        }
    },

    sourceStatistics: async (req, res, next) => {
        try {
            let newSourceStatistics = new SourceStatistics({
                way: req.body.way,
                isDelete: 0,
            })
            await newSourceStatistics.save()
            return res.ok('来源添加成功', newSourceStatistics)
        } catch (e) {
            next(e)
        }
    },

    getVoucherList: async (req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            option.status = 1
            if (req.body.title) {
                option.title = new RegExp(req.body.title, 'i')
            }

            if (req.body.store) {
                option.store = { $in: req.body.store }
            }
            let count = await Voucher.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Voucher.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },
    getOneVoucher: async (req, res, next) => {
        try {
            let voucher = await Voucher.findOne({ _id: req.body.id, isDelete: 0 }).populate('store').exec()
            res.ok('获取成功', voucher)
        } catch (e) {
            next(e)
        }
    },
    submitVoucherOrder: async (req, res, next) => {
        try {
            let voucher = await Voucher.findOne({ _id: req.body.voucher, isDelete: 0 }).exec()
            if (Number(req.body.amount) > voucher.limit) {
                return res.send({ code: 201, msg: '超过购买数量限制' })
            }
            if (Number(req.body.amount > voucher.currentCount)) {
                return res.send({ code: 201, msg: '库存不足' })
            }
            let newOrder = new Order({
                unionID: req.body.unionid,
                openid: req.body.openid,
                products: [{ voucher: req.body.voucher, amount: req.body.amount }], //// {product: productSubId,amount : 数字}
                updatedAt: new Date(),
                total: voucher.discountPrice * req.body.amount, //总价
                status: 0,
                isDelete: 0,
                type: 1
            })
            await newOrder.save()
            res.ok('提交成功', newOrder)
        } catch (e) {
            next(e)
        }
    },
    voucherOrderPaymentSuccess: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.order, isDelete: 0 }).exec()
            order.status = 1
            order.updatedAt = new Date()
            order.paidAt = new Date()
            await order.save()
            for (let i = 0; i < parseInt(order.products[0].amount); i++) {
                let newMyVoucher = new MyVoucher({
                    openid: req.body.openid,
                    unionID: req.body.unionid,
                    voucher: order.products[0].voucher,
                    amount: 1,
                    status: 0,//0未使用，1使用
                    updatedAt: new Date(),
                    isDelete: 0
                })
                await newMyVoucher.save()
            }
            res.ok('抵用券购买成功')
        } catch (e) {
            next(e)
        }
    },
    voucherOrderPaymentFailed: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.order, isDelete: 0 }).exec()
            res.ok('抵用券购买失败', order)
        } catch (e) {
            next(e)
        }
    },
    useVoucher: async (req, res, next) => {
        try {
            let nowDate = new Date()
            let tms = parseInt(req.body.tms)
            let timestamp = new Date().getTime()
            let staff = await Staff.findOne({ openid: req.body.openid, isDelete: 0 }).exec()
            if ((timestamp - tms) > 900000) {
                res.send({ code: 201, msg: "二维码超时" })
            } else {
                let myVoucher = await MyVoucher.findOne({ openid: req.body.userOpenid, order: req.body.voucher }).exec()
                let voucher = await Voucher.findOne({ _id: myVoucher.voucher }).exec()
                if (myVoucher.status == 1) {
                    // let otherMyVoucher = await MyVoucher.findOne({openid:req.body.userOpenid,voucher:req.body.voucher,status:0}).exec()
                    // if(otherMyVoucher == null){
                    res.send({ code: 201, msg: "抵用券已被使用" })
                    // }else{
                    //     otherMyVoucher.status = 1
                    //     await otherMyVoucher.save()
                    //     res.ok('使用成功', otherMyVoucher)
                    // }
                } else if (voucher.useExpireType == 1) {
                    if (nowDate < voucher.useStartDate) {
                        res.send({ code: 201, msg: "未到开始使用日期" })
                    } else if (nowDate > voucher.useExpireDate) {
                        res.send({ code: 201, msg: "已超过使用时间" })
                    } else if (myVoucher.status == 0) {
                        myVoucher.status = 1
                        myVoucher.useDate = new Date()
                        myVoucher.staff = staff._id
                        await myVoucher.save()
                        let order = await Order.findOne({ _id: myVoucher.order, isDelete: 0 }).exec()
                        order.useDate = new Date()
                        order.staff = staff._id
                        await order.save()
                        res.ok('使用成功', myVoucher)
                    }
                } else if (voucher.useExpireType == 2) {
                    if (nowDate > moment(myVoucher.createdAt).add(myVoucher.useExpireDay, 'days')) {
                        res.send({ code: 201, msg: "已超过使用时间" })
                    } else if (myVoucher.status == 0) {
                        myVoucher.status = 1
                        myVoucher.useDate = new Date()
                        myVoucher.staff = staff._id
                        await myVoucher.save()
                        let order = await Order.findOne({ _id: myVoucher.order, isDelete: 0 }).exec()
                        order.useDate = new Date()
                        order.staff = staff._id
                        await order.save()
                        res.ok('使用成功', myVoucher)
                    }
                }
            }
        } catch (e) {
            next(e)
        }
    },
    getUserVoucherList: async (req, res, next) => {
        try {
            let option = {}
            option.openid = req.body.openid
            if (req.body.status) {
                option.status = req.body.status
            }
            let count = await MyVoucher.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await MyVoucher.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('查询成功', result)
        } catch (e) {
            next(e)
        }
    },
    getOneUserVoucher: async (req, res, next) => {
        try {
            let myVoucher = await MyVoucher.findOne({ openid: req.body.openid, order: req.body.id }).populate('voucher order').exec()
            if (myVoucher) {
                res.ok('查询成功', myVoucher)
            } else {
                res.send({ code: 201, msg: '未查询到抵用券' })
            }
        } catch (e) {
            next(e)
        }
    },
    getPrepayId: async (req, res, next) => {
        try {
            let params = wxpay.generateParam(req.body.openid, req.body.orderId, parseInt(req.body.price * 100), req.body.title)
            var xml = params[0]
            var theparams = params[1]
            wxpay.wxPay(xml, function (err, response, body) {
                console.log(body, 'jbob')
                if ((body.return_code[0] == 'SUCCESS') && (body.result_code[0] == 'SUCCESS')) {
                    var payParams = wxpay.payParam(body)
                    console.log(payParams)
                    res.send({ 'code': 200, 'data': payParams })
                }
                else if ((body.return_code[0] == 'SUCCESS') && (body.result_code[0] == 'FAIL')) {
                    console.log('payproblem', body)
                    if (body.err_code[0] == 'ORDERPAID') {
                        res.send({ 'code': 201, msg: '订单号已支付' })
                    }
                    else if (body.err_code[0] == 'OUT_TRADE_NO_USED') {
                        res.send({ 'code': 201, msg: '订单号已被使用' })
                    }
                    else {
                        res.send({ 'code': 400, msg: body.err_code, type: 'xxx' })
                    }

                }
                else {
                    res.send({ 'code': 400, msg: body, type: '111' })
                }

            })
        } catch (e) {
            next(e)
        }
    },
    orderPaymentSuccess: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.order, isDelete: 0 }).exec()
            order.status = 1
            order.paidAt = new Date()
            await order.save()
            res.ok('订单支付成功')
        } catch (e) {
            next(e)
        }
    },
    orderPaymentFailed: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.order, isDelete: 0 }).exec()
            res.ok('订单支付失败', order)
        } catch (e) {
            next(e)
        }
    },
    applicationReimburse: async (req, res, next) => {
        try {
            let order = await Order.findOne({ _id: req.body.order, openid: req.body.openid, isDelete: 0 }).exec()
            if (order == null) {
                return res.send({ 'code': 201, msg: '未查询到订单' })
            }
            if (order.status == 2) {
                return res.send({ 'code': 201, msg: '已申请退款，请勿重复申请' })
            }
            let newReimburse = new Reimburse({
                order: req.body.order,
                shipping: order.shipping,
                status: 0, // 0 待处理，1，处理退款/积分,2 拒绝
                isDelete: 0,
                openid: req.body.openid,
                updatedAt: new Date(),
                images: req.body.images
            })
            await newReimburse.save()
            order.updatedAt = new Date()
            order.status = 3
            order.reimburse = newReimburse._id
            await order.save()
            res.ok('申请退款成功', order)
        } catch (e) {
            next(e)
        }
    },

    confirmOrderWithoutMoney: async (req, res, next) => {
        try {
            processPaymentOrder(req.body.id, req, res)
        } catch (e) {
            next(e)
        }
    },

    uploadBillImage: async (req, res, next) => {
        try {
            let expenseHistory = await ExpenseHistory.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            expenseHistory.billImage = req.body.billImage
            expenseHistory.updatedAt = new Date()
            await expenseHistory.save()
            res.ok('添加账单图片成功', expenseHistory)
        } catch (e) {
            next(e)
        }
    },

    uploadimage: async (req, res, next) => {
        var form = new multiparty.Form();
        form.parse(req, function (err, fields, files) {
            // if (userValidation(req.session.id,fields.session[0],res)){
            var temp = ''
            var path = fields.path[0]
            var id = fields.objectid[0]
            var filename = fields.filename[0]
            var type = fields.type[0]
            console.log('jojkk', type, id, 'sdds')
            if (Object.keys(files) == 0) {
                res.send({ 'code': 201 })
            } else {
                cos.putObject({
                    Bucket: 'yifei-1300737392',
                    Region: 'ap-beijing',
                    Key: '/image/' + id + '_' + filename, // 这里传入前缀
                    Body: fs.readFileSync(files.image[0].path),
                }, function (err, data) {
                    if (err == null) {
                        if (type == 'leave') {
                            LeaveRecord.findOneAndUpdate({ _id: id }, { $push: { imageLink: data.Location } }).exec(function (e) {
                                res.send({ 'code': 200 })
                            })

                        } else if (type == 'reimburse') {
                            Reimburse.findOneAndUpdate({ _id: id }, { $push: { imageLink: data.Location } }).exec(function (e) {
                                res.send({ 'code': 200 })
                            })

                        }
                    }
                });
            }

        })
    },
}


function initializeUser(openid, unionid, cellphone, userinfo, way, QRStore, QRType, callback) {
    User.findOne({ $or: [{ unionID: unionid }, { openid: openid }] }, function (err, data) {
        if (data == null) {
            var newuser = new User()
            newuser.openid = openid,
                newuser.unionID = unionid,
                newuser.date = new Date(),
                newuser.cellphone = cellphone,
                newuser.lastFour = cellphone.substr(cellphone.length - 4, 4),
                newuser.gender = parseInt(userinfo.gender) || undefined,
                newuser.city = userinfo.city,
                newuser.province = userinfo.province,
                newuser.country = userinfo.country,
                newuser.avatar = userinfo.avatarUrl,
                newuser.nickName = userinfo.nickName,
                newuser.usertype = "",
                newuser.vip = 0,
                newuser.isDelete = 0,
                newuser.way = way,
                newuser.QRStore = QRStore
            newuser.QRType = QRType
            newuser.save(function (err) {
                if (!err) {
                    initializemember(unionid, openid, cellphone)
                    callback(err, newuser)
                }
            })
        } else {
            if (data.gender == 0) {
                data.gender = parseInt(userinfo.gender)
            }
            if(data.city == undefined || data.city == ""){
                if(userinfo.city != undefined){
                    data.city = userinfo.city
                }
            }
            // if (data.city == "") {
            //     data.city = userinfo.city || ""
            // }
            if (data.province == "") {
                data.province = userinfo.province
            }
            if (data.country == "") {
                data.country = userinfo.country
            }
            if (data.avatar == "") {
                data.avatar = userinfo.avatarUrl
            }
            if (data.nickName == "") {
                data.nickName = userinfo.nickName
            }
            if (!data.unionID) {
                data.unionID = unionid
            }
            if (!data.way) {
                data.way = way
            }
            if (!data.QRStore) {
                data.QRStore = QRStore
            }
            if (!data.QRType) {
                data.QRType = QRType
            }
            data.save(function (err) {

                callback(null)


            })
        }
    })
}

function randomsixdigit() {
    var sixdigitnumber = Math.floor((Math.random() * 900000) + 100000 - 1);
    return parseInt(sixdigitnumber)
}



function saveOneImage(filename, file, path, callback) {
    mkdirp(path, function (err) {

        //
        // fs.writeFile(filename, file, 'base64',function (err) {
        //  callback(err)
        // })
        var path1 = path + filename
        var path2 = path + 't_' + filename
        fs.writeFile(path1, file, 'base64', function (err) {
            easyimage.resize({
                src: path1,
                dst: path1,
                width: 800

            }).then(function (err, stdout, stderr) {
                easyimage.resize({
                    src: path1,
                    dst: path2,
                    width: 250,
                    height: 250

                }).then(function (err, stdout, stderr) {
                    callback(err)
                })
            })
        })
    })
}

function randomString(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
async function initializemember(unionid, openid, cellphone) {
    let member = await Member.findOne({ openid, isDelete: 0 }).exec()
    if (member == null) {
        let newmember = new Member({
            openid: openid,
            unionID: unionid,
            code: "",
            point: 0,
            updatedAt: new Date(),
            isDelete: 0,
        })
        await newmember.save()
        let newUserPoint = new UserPoint({
            openid: openid,
            unionID: unionid,
            cellphone: cellphone,
            updatedAt: new Date(),
            total: 0,
            current: 0,
            isDelete: 0,
        })
        await newUserPoint.save()
    }
}

function getRandom(start, end) {
    var length = end - start;
    var num = parseInt(Math.random() * (length) + start);
    return num;
}


async function processPaymentOrder(id, req, res) {
    // let order = await Order.findOneAndUpdate({ _id: id }, { wxPayID: transaction_id, status: 1, updatedAt: new Date(), paidAt: new Date() }).exec()
    let order = await Order.findOne({ _id: id }).exec()
    let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
    let member = await Member.findOne({ openid: order.openid, isDelete: 0 }).exec()
    let userPoint = await UserPoint.findOne({ openid: order.openid, isDelete: 0 }).exec()
    if (order.amountOfUsePoint > userPoint.current) {
        return res.send({ code: 201, msg: "积分不足" })
    }
    if (order.usePoint == 0) {
        return res.send({ code: 201, msg: "此订单未选择使用积分支付" })
    } else if (order.usePoint == 1) {
        order.status = 1
        order.updatedAt = new Date()
        order.paidAt = new Date()
        await order.save()




        // let newPointHistory = new PointHistory({
        //     openid: order.openid,
        //     unionID: order.unionID,
        //     order: order._id,
        //     expenseDate: new Date(),
        //     manual: 0, // 1位人工，0为自动
        //     amount: order.amountOfUsePoint, // 变动的积分数量
        //     type: 1, // 0 为加，1为减
        //     isDelete: 0,
        // })
        // await newPointHistory.save()
        // member.point = member.point - order.amountOfUsePoint
        // member.updatedAt = new Date()
        // await member.save()
        // userPoint.current = userPoint.current - order.amountOfUsePoint
        // userPoint.updatedAt = new Date()
        // await userPoint.save()
        // for (let i = 0; i < order.products.length; i++) {
        //     if (Object.keys(order.products[i])[0] == 'voucher') {
        //         for (let i = 0; i < parseInt(order.products[i].amount); i++) {
        //             let newMyVoucher = new MyVoucher({
        //                 openid: order.openid,
        //                 unionID: order.unionID,
        //                 voucher: order.products[i].voucher,
        //                 amount: 1,
        //                 status: 0,//0未使用，1使用
        //                 updatedAt: new Date(),
        //                 order: order._id,
        //                 isDelete: 0
        //             })
        //             await newMyVoucher.save()
        //         }
        //     }
        // }
        // wxPublicAccessToken.getAccessToken(function (token) {
        //     request({
        //         url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
        //         method: "POST",
        //         timeout: 10000,
        //         encoding: null,
        //         json: {
        //             "code": member.code,
        //             "card_id": memberCardNumber,
        //             "bonus": member.point
        //         }
        //     }, function (error, response, body) {
        //         console.log(error)
        //         res.send({ 'code': 200 })
        //     })
        // })
        // return








        if (order.type == 0) {
            if (order.usePoint == 1) {
                let newPointHistory = new PointHistory({
                    openid: order.openid,
                    unionID: order.unionID,
                    order: order._id,
                    expenseDate: new Date(),
                    manual: 0, // 1位人工，0为自动
                    amount: order.amountOfUsePoint, // 变动的积分数量
                    type: 1, // 0 为加，1为减
                    isDelete: 0,
                })
                await newPointHistory.save()
                member.point = member.point - order.amountOfUsePoint
                member.updatedAt = new Date()
                await member.save()
                userPoint.current = userPoint.current - order.amountOfUsePoint
                userPoint.updatedAt = new Date()
                await userPoint.save()
                wxPublicAccessToken.getAccessToken(function (token) {
                    request({
                        url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                        method: "POST",
                        timeout: 10000,
                        encoding: null,
                        json: {
                            "code": member.code,
                            "card_id": memberCardNumber,
                            "bonus": member.point
                        }
                    }, function (error, response, body) {
                        console.log(error)
                        res.send({ 'code': 200, data: order._id })
                    })
                })
            }
        } else if (order.type == 1) {
            // order.updatedAt = new Date()
            // order.paidAt = new Date()
            // await order.save()
            for (let i = 0; i < parseInt(order.products[0].amount); i++) {
                let voucher = await Voucher.findOne({ _id: order.products[i].voucher, isDelete: 0 }).exec()
                voucher.currentCount = voucher.currentCount - parseInt(order.products[i].amount)
                await voucher.save()
                let newMyVoucher = new MyVoucher({
                    openid: order.openid,
                    unionID: order.unionID,
                    voucher: order.products[0].voucher,
                    amount: 1,
                    status: 0,//0未使用，1使用
                    updatedAt: new Date(),
                    order: order._id,
                    isDelete: 0
                })
                await newMyVoucher.save()
            }
            let newPointHistory = new PointHistory({
                openid: order.openid,
                unionID: order.unionID,
                order: order._id,
                expenseDate: new Date(),
                manual: 0, // 1位人工，0为自动
                amount: order.amountOfUsePoint, // 变动的积分数量
                type: 1, // 0 为加，1为减
                isDelete: 0,
            })
            await newPointHistory.save()
            member.point = member.point - order.amountOfUsePoint
            member.updatedAt = new Date()
            await member.save()
            userPoint.current = userPoint.current - order.amountOfUsePoint
            userPoint.updatedAt = new Date()
            await userPoint.save()
            wxPublicAccessToken.getAccessToken(function (token) {
                request({
                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                    method: "POST",
                    timeout: 10000,
                    encoding: null,
                    json: {
                        "code": member.code,
                        "card_id": memberCardNumber,
                        "bonus": member.point
                    }
                }, function (error, response, body) {
                    console.log(error)
                    res.send({ 'code': 200, data: order._id })
                })
            })
            // res.send({ 'code': 200,data:order._id })
        }
    }
}